package namespace

import (
	"context"
	"kms-backend/config"
	"kms-backend/controllers"
	"kms-backend/utils/logs"

	"github.com/gin-gonic/gin"
	corev1 "k8s.io/api/core/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)

func Create(r *gin.Context) {
	// 新增
	logs.Debug(nil, "创建命名空间")

	returnData := config.ReturnData{}
	// 生成clientSet, 基础数据basicInfo
	clientSet, basicInfo, err := controllers.BasicInit(r, nil)
	if err != nil {
		returnData.Message = err.Error()
		returnData.Status = 400
		r.JSON(200, returnData)
		return
	}

	// 操作资源
	var namespace corev1.Namespace
	namespace.Name = basicInfo.Name
	_, err = clientSet.CoreV1().Namespaces().Create(context.TODO(), &namespace, metav1.CreateOptions{})
	if err != nil {
		msg := "命名空间创建失败" + err.Error()
		logs.Error(nil, "集群"+basicInfo.ClusterId+msg)
		returnData.Message = msg
		returnData.Status = 400
	} else {
		msg := "创建namespace成功"
		logs.Info(nil, "集群"+basicInfo.ClusterId+"中命名空间"+namespace.Name+"创建成功")
		returnData.Message = msg
		returnData.Status = 200
	}
	r.JSON(200, returnData)

}
